package com.wuhao.jdqlib.ui

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.ParcelUuid
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.coder.vincent.smart_toast.SmartToast
import com.drake.brv.utils.divider
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.drake.channel.sendEvent
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.wuhao.jdqlib.R
import com.wuhao.jdqlib.constants.AppConfig
import com.wuhao.jdqlib.data.BleToConnectEvent
import com.wuhao.jdqlib.databinding.ActivityBleListBinding
import com.wuhao.jdqlib.databinding.ItemDeviceBleInfoBinding
import com.wuhao.jdqlib.utils.throttleClick
import com.wuhao.shootclient.base.EngineActivity
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


@SuppressLint("MissingPermission")
class BleListActivity : EngineActivity<ActivityBleListBinding>(R.layout.activity_ble_list) {

    private var bleAdapter: BluetoothAdapter? = null
    private var bleScanner: BluetoothLeScanner? = null
    private lateinit var scanCallback: ScanCallback

    private var deviceList: ArrayList<ScanResult> = arrayListOf()
    private lateinit var viewModel: BleListViewModel

    override fun initView() {
        val layoutParams = this.window.attributes
        layoutParams.height =
            resources.displayMetrics.heightPixels - (resources.displayMetrics.heightPixels / 3)
        layoutParams.width =
            resources.displayMetrics.widthPixels / 2
        window.attributes = layoutParams

        binding.lifecycleOwner = this
        viewModel = ViewModelProvider(this)[BleListViewModel::class.java]
        binding.m = viewModel

        bleAdapter = getBluetoothAdapter()
        // 通过创建的蓝牙适配器检查本机是否支持BLE功能
        if (bleAdapter == null) {
            Toast.makeText(this, "本机不支持BLE", Toast.LENGTH_SHORT).show()
            finishTransition()
            return
        }

        initBle()

        initRecyclerView()

        initListener()

    }

    private fun initListener() {
        binding.btnCancel.throttleClick {
            if (viewModel.isScanning.value == true) {
                finishTransition()
            } else {
                viewModel.isScanning.value = true
                //检查权限、重新扫描
                checkPermissions()
            }

        }
    }


    private fun initBle() {
        bleScanner = bleAdapter!!.bluetoothLeScanner

        // 设置扫描回调
        scanCallback = object : ScanCallback() {
            override fun onScanResult(callbackType: Int, result: ScanResult) {
                super.onScanResult(callbackType, result)
                if (result.device?.name?.isNotEmpty() == true) {
                    processingResults(result)
                }
            }

            override fun onBatchScanResults(results: List<ScanResult>) {
                deviceList.clear()
                for (result in results) {
                    deviceList.add(result)
                }
            }

            override fun onScanFailed(errorCode: Int) {
                super.onScanFailed(errorCode)
                binding.stateLayout.showEmpty()
            }
        }
    }

    private fun startBleScan() {
        lifecycleScope.launch {
            try {
                deviceList.clear()
                binding.rvBleList.models = deviceList

                // 创建扫描过滤器
                val filters: MutableList<ScanFilter> = ArrayList()
                //只扫描指定打印机
                val serviceUuid = ParcelUuid.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e")
                val filter = ScanFilter.Builder().setServiceUuid(serviceUuid).build()
                filters.add(filter)

                // 创建扫描设置
                val settings = ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_BALANCED) // 或其他模式
                    .build()
                viewModel.isScanning.value = true
                // 开始扫描
                bleScanner?.startScan(filters, settings, scanCallback)

                //每次扫描持续15秒
                delay(15000)

                //如果扫描结束，没有一个设备就显示缺省
                if (deviceList.isEmpty()) {
                    binding.stateLayout.showEmpty()
                }
                viewModel.isScanning.value = false
                stopBleScan()

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun initRecyclerView() {
        binding.rvBleList.linear().divider {
            setDivider(1, true)
            setColor(getColor(R.color.bg_item_img))
        }.setup {
            addType<ScanResult>(R.layout.item_device_ble_info)

            onBind {
                val model = getModel<ScanResult>()
                val holder = getBinding<ItemDeviceBleInfoBinding>()
                if (model.device.name == AppConfig.bleName && model.device.address == AppConfig.bleMac) {
                    holder.paired.text = getString(R.string.before_time_paired)
                } else {
                    holder.paired.text = getString(R.string.paired)
                }
                holder.name.text = model.device.name
                holder.signalView.setSignalValue(getValueByRssi(model.rssi))
                holder.rssi.text = "${model.rssi}dBm"
                holder.address.text = model.device.address
            }
            onClick(R.id.rl_item) {
                val model = getModel<ScanResult>()
                sendEvent(BleToConnectEvent(model.device.address, model.device.name, true))
                finishTransition()
            }
        }.models = deviceList

        binding.stateLayout.onEmpty {
            findViewById<ImageView>(R.id.iv).setImageResource(R.drawable.img_ble_empty)
            findViewById<TextView>(R.id.msg).text = "未搜索到蓝牙设备，请重新搜索"
        }
    }

    /**
     * 转换信号等级
     */
    private fun getValueByRssi(rssi: Int): Int {
        return if (rssi > -60) {
            5
        } else if (rssi > -70) {
            4
        } else if (rssi > -75) {
            3
        } else if (rssi > -80) {
            2
        } else if (rssi > -85) {
            1
        } else {
            0
        }
    }

    private fun getBluetoothAdapter(): BluetoothAdapter? {
        // 获取BluetoothManager系统服务
        val bluetoothManager: BluetoothManager =
            this.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        // 通过BluetoothManager获取BluetoothAdapter
        val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.adapter

        return bluetoothAdapter
    }

    override fun initData() {
        //检查权限、扫描蓝牙
        checkPermissions()
    }

    override fun onPause() {
        viewModel.isScanning.value = false
        stopBleScan()
        super.onPause()
    }

    /**
     * 更新蓝牙
     */
    private fun processingResults(result: ScanResult) {
        val index =
            deviceList.indexOfFirst { it.device.address == result.device.address }
        if (index != -1) {
            deviceList[index] = result
        } else {
            deviceList.add(result)
        }
        binding.rvBleList.models = deviceList

        if (deviceList.isNotEmpty()) {
            binding.stateLayout.showContent()
        }
    }

    override fun onDestroy() {
        // 停止扫描
        stopBleScan()
        super.onDestroy()
    }

    private fun stopBleScan() {
        if (bleAdapter != null && bleAdapter!!.isEnabled) {
            bleScanner?.stopScan(scanCallback)
        }
    }


    /**
     * 检查权限问题
     */
    private fun checkPermissions() {
        val arrayPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            listOf(
                android.Manifest.permission.BLUETOOTH_CONNECT,
                android.Manifest.permission.BLUETOOTH_SCAN,
                android.Manifest.permission.ACCESS_FINE_LOCATION
            )
        } else {
            listOf(
                android.Manifest.permission.BLUETOOTH,
                android.Manifest.permission.BLUETOOTH_ADMIN,
                android.Manifest.permission.ACCESS_FINE_LOCATION
            )
        }
        XXPermissions.with(this@BleListActivity)
            .permission(
                arrayPermission
            ).request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        Toast.makeText(this@BleListActivity, "权限未授予，无法使用蓝牙", Toast.LENGTH_SHORT).show()
                    }else{
                        checkBleEnable()
                    }
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        SmartToast.emotion().warning("注意：被永久拒绝授权，会影响系统正常使用")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(this@BleListActivity, permissions)
                    } else {
                        SmartToast.emotion().warning("系统获取权限失败，会影响系统正常使用")
                    }
                }
            })
    }

    /**
     * 检查蓝牙是否可用、开关是否打开状态
     */
    private fun checkBleEnable() {
        val bleAdapter = getBluetoothAdapter()
        if (bleAdapter != null) {//是否开启蓝牙
            if (bleAdapter.isEnabled) {
                //扫描蓝牙
                startBleScan()
            } else {
                // 蓝牙没有开启，请求用户开启
                val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                enableBtLauncher.launch(enableBtIntent)
            }
        } else {
            Toast.makeText(this, "该设备不支持蓝牙功能", Toast.LENGTH_SHORT).show()
        }
    }

    // 创建一个ActivityResultLauncher来启动蓝牙开启请求
    private val enableBtLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                //扫描蓝牙
                startBleScan()
            } else {
                // 用户拒绝开启蓝牙
                Toast.makeText(this, "打开蓝牙开关才能使用该功能", Toast.LENGTH_SHORT).show()
            }
        }
}

